<template>
    <view class="login-container" :style="{ 'justify-content': loginType ? 'center' : '' }">
        <!-- 圆形Logo -->
        <view class="logo-container">
            <image src="/static/appLogo.jpeg" mode="aspectFit" class="logo"></image>
        </view>

        <!-- 表单区域 -->
        <view class="form-container">
            <wd-transition :show="show" name="fade">
                <!-- 手机号输入框和验证码按钮 -->
                <template v-if="!loginType">
                    <view class="phone-input-group">
                        <input v-model="form.phone" type="number" placeholder="请输入手机号码" maxlength="11"
                            class="phone-input" />
                        <button class="send-btn" :disabled="isCountingDown" @click="sendVerificationCode">
                            {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                        </button>
                    </view>
                    <!-- 验证码输入框 -->
                    <view class="input-group">
                        <input v-model="form.code" type="number" placeholder="请输入验证码" maxlength="6" class="input" />
                    </view>
                </template>
            </wd-transition>

            <!-- 登录按钮 -->
            <button class="login-btn" v-if="!loginType" :class="{ active: canSubmit }" :disabled="!canSubmit"
                @click="handleLogin">
                登&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录
            </button>
            <button class="login-btn" v-else :disabled="!isAgreed" :class="{ active: isAgreed }"
                style="background-color: #55946d;" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
                授权登录
            </button>
            <view class="login-type" @click="loginType = !loginType">{{ !loginType ? '授权登录' : '验证码登录' }}</view>
        </view>

        <!-- 协议勾选 (固定在底部) -->
        <view class="agreement-footer">
            <label class="agreement-label">
                <wd-checkbox checked-color="#55946d" v-model="agreed" @change="handleChange"></wd-checkbox>
                <text>阅读并同意</text>
                <text class="link" @click="navigateToAgreement('user')">《用户服务协议》</text>
                <text>和</text>
                <text class="link" @click="navigateToAgreement('privacy')">《隐私政策》</text>
            </label>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { miniLogin, sendCode, tokenLogin } from '@/api/apiList'
import { onLoad } from '@dcloudio/uni-app'
import { getToken, getPhone } from '@/pages/login/getUserPhone'

// 获取微信code
let wxCode = ref('')
let accessToken = ref('')
const getWxCode = (code) => {
    uni.login({
        success: async (res) => {
            wxCode.value = res.code
            // accessToken.value = await getToken() // 小程序登录获取access_token
            // const phoneRes = await getPhone(accessToken.value, code) // 小程序登录获取手机号
            // telCode: phoneRes?.phone_info?.phoneNumber
            login({ wxCode: code, type: 0, authCode: res.code })
        }
    })
}

// onLoad(() => {
//     getWxCode()
// })

// 微信授权登录
const getPhoneNumber = async (e) => {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
        getWxCode(e.detail.code)
    } else {
        // 登录失败
        uni.showToast({
            title: '您取消了授权',
            icon: 'none'
        })
    }
}

const isAgreed = computed(() => {
    return agreed.value
})

// 登录
const login = async (data) => {

    const params = {
        ...data
    }
    uni.showLoading({
        title: '登录中'
    })
    const res = await miniLogin(params)
    if (res.code == 200) {
        uni.hideLoading()
        uni.setStorageSync('token', res.msg)
        uni.showToast({
            title: '登录成功',
            icon: 'none'
        })
        setTimeout(() => {
            uni.navigateBack()
        }, 1000)
    } else {
        uni.hideLoading()
        uni.showToast({
            title: '登录失败',
            icon: 'none'
        })
    }
}

// 表单数据
const form = ref({
    phone: '',
    code: '',
})

const loginType = ref(true)
const show = ref(true)
let agreed = ref(false)
const handleChange = ({ value }) => {
    agreed.value = value
}

// 倒计时相关
const countdown = ref(0)
const isCountingDown = ref(false)
let timer = null

// 计算属性：是否可以提交
const canSubmit = computed(() => {
    return (
        /^1[3-9]\d{9}$/.test(form.value.phone) &&
        form.value.code.length && agreed.value
    )
})

const testForm = {
    "userNmae": "chargeStation",
    "pwd": "chargeStation@#123"
}

// 获取验证码
const getSmsCode = async () => {
    const res = await sendCode({
        phonenumber: form.value.phone
    })
    if (res.code == 200) {
        // form.value.code = res.msg
        uni.showToast({
            title: '验证码已发送',
            icon: 'none'
        })
    }
}

// 发送验证码
const sendVerificationCode = () => {
    if (!/^1[3-9]\d{9}$/.test(form.value.phone)) {
        uni.showToast({
            title: '请输入正确的手机号码',
            icon: 'none'
        })
        return
    }

    // 开始倒计时
    isCountingDown.value = true
    countdown.value = 60

    // 清除之前的定时器
    if (timer) clearInterval(timer)

    timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
            clearInterval(timer)
            isCountingDown.value = false
        }
    }, 1000)
    getSmsCode()
    // 这里调用发送验证码的API

}

// 跳转到协议页面
const navigateToAgreement = (type) => {
    uni.navigateTo({
        url: `/pages/login/agreement?type=${type}`
    })
}

// 处理登录
const handleLogin = async () => {
    uni.showLoading({
        title: '登录中...'
    })

    login({
        telCode: form.value.phone,
        code: form.value.code,
        type: 1
    })

}

// 验证码登录
const handleCodeLogin = async () => {
    const res = await tokenLogin(form.value)
    if (res.code == 200) {
        uni.hideLoading()
        uni.showToast({
            title: '登录成功',
            icon: 'none'
        })
        uni.setStorageSync('token', res.token)
        setTimeout(() => {
            uni.navigateBack()
        }, 1000)
    }
}

// 组件卸载时清除定时器
onUnmounted(() => {
    if (timer) clearInterval(timer)
})
</script>

<style lang="scss" scoped>
.login-container {
    padding: 40rpx;
    /* 底部留出协议位置 */
    display: flex;
    flex-direction: column;
    align-items: center;
    min-height: 100vh;
    box-sizing: border-box;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.logo-container {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    overflow: hidden;
    background-color: #f5f5f5;
    margin-bottom: 80rpx;

    .logo {
        width: 100%;
        height: 100%;
    }
}

.form-container {
    width: 100%;
}

/* 手机号输入组 */
.phone-input-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 40rpx;


    .phone-input {
        flex: 1;
        height: 90rpx;
        padding: 0 30rpx;
        font-size: 28rpx;
        border: 1px solid #e5e5e5;
        border-radius: 12rpx;
        overflow: hidden;
        width: 100%;
    }

    .divider {
        width: 1px;
        height: 40rpx;
        background-color: #e5e5e5;
    }

    .send-btn {
        height: 90rpx;
        margin-left: 10rpx;
        line-height: 90rpx;
        padding: 0;
        background-color: transparent;
        color: #55946d;
        font-size: 24rpx;
        border: none;
        text-align: right;
        font-size: 30rpx;

        &::after {
            border: none;
        }

        &[disabled] {
            color: #999;
        }
    }
}

/* 验证码输入框 */
.input-group {
    margin-bottom: 60rpx;

    .input {
        height: 90rpx;
        padding: 0 30rpx;
        border: 1px solid #e5e5e5;
        border-radius: 12rpx;
        font-size: 28rpx;
    }
}

/* 登录按钮 */
.login-btn {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    background-color: #cccccc;
    color: white;
    border-radius: 12rpx;
    font-size: 32rpx;
    border: none;

    &.active {
        background-color: #55946d;
    }

    &[disabled] {
        background-color: #cccccc !important;
    }
}

/* 底部协议 */
.agreement-footer {
    // position: fixed;
    // bottom: 30rpx;
    // left: 0;
    // right: 0;
    // padding: 0 60rpx;
    margin-top: 60rpx;
    font-size: 30rpx;
    color: #666;
    text-align: center;

    .agreement-label {
        display: flex;
        align-items: center;
        justify-content: center;
    }

  .agreement-label text {
    font-size: 24rpx
  }

    .link {
        color: #55946d;
        margin: 0 6rpx;
    }
}

/* 自定义圆形复选框 */
checkbox {
    border-radius: 50%;
    transform: scale(0.8);
    margin-right: 8rpx;
}

.login-type {
    text-align: right;
    color: #55946d;
    font-size: 30rpx;
    margin-top: 30rpx;
}
</style>
